﻿using UnityEngine;
using System.Collections.Generic;
using ProtoBuf.Message;

namespace Room
{
    public class NetUnionFightResource : NetUnionFightBase
    {
        public Dictionary<long, InstUFResourcePoint> resources = new Dictionary<long, InstUFResourcePoint>();

        public NetUnionFightResource(RoomUnionFight unionFight, RoomCharactorManager mgr, RoomNetUnionFight net)
            : base(unionFight, mgr, net)
        {
        }

        public override void Enter()
        {
            base.Enter();
            resources.Clear();
        }

        public override void Leave()
        {
            base.Leave();
            resources.Clear();
        }

        public override RoomCharactor CreateCharactor(long uuid)
        {
            var res = resources[uuid];
            charactorManager.CreateUnionResource(uuid, res, postions[uuid]);
            resources[uuid] = res;
            var charactor = GetCharactor(uuid);
            return charactor;
        }

        public override void ClearCharactorData(long uuid)
        {
            base.ClearCharactorData(uuid);
            if (resources.ContainsKey(uuid))
                resources.Remove(uuid);
        }

        /// <summary>
        /// 刷新资源
        /// </summary>
        /// <param name="msg"></param>
        public void ResourceRefresh(SCUFResourcePoint msg)
        {
            for(int i = 0;i<msg.point.Count;i++)
            {
                var uuid = msg.point[i].guid;
                resources[uuid] = msg.point[i];
                var pos = new Vector3(msg.local[i].x, msg.local[i].y, msg.local[i].z);
                postions[uuid]=pos;
                states[uuid] = -1;
                
                var charactor = GetCharactor(uuid,false);
                if (charactor == null)
                {
                    charactor = CreateCharactor(uuid);
                }

                UpdatePosition(uuid, pos);
            }
           
        }

        /// <summary>
        /// 资源出生
        /// </summary>
        /// <param name="msg"></param>
        public void ResourceSpawn(SCUFResourcePointSpawn msg)
        {
            for (int i = 0; i < msg.point.Count; ++i)
            {
                var uuid =  msg.point[i].guid;
                var pos = msg.pos[i];
                var vec = new Vector3(pos.x, pos.y, pos.z);
                postions[uuid] = vec;
                states[uuid] = -1;
                resources[uuid] = msg.point[i];

                var charactor = GetCharactor(uuid);
                if (charactor == null)
                {
                    charactor = CreateCharactor(uuid);
                }

                UpdatePosition(uuid, vec);
            }
        }

        /// <summary>
        /// 资源消失
        /// </summary>
        /// <param name="msg"></param>
        public void ResourceDisappear(string guid)
        {
            string uuid =  guid;
            DestroyCharactor(uuid);
        }
    }
}
